/*
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */

package com.l2emu.gameserver;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Calendar;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.mmocore.network.SelectorConfig;
import org.mmocore.network.SelectorThread;

import com.l2emu.Config;
import com.l2emu.L2DatabaseFactory;
import com.l2emu.Server;
import com.l2emu.gameserver.cache.CrestCache;
import com.l2emu.gameserver.cache.HtmCache;
import com.l2emu.gameserver.communitybbs.Manager.ForumsBBSManager;
import com.l2emu.gameserver.datatables.AccessLevels;
import com.l2emu.gameserver.datatables.AdminCommandAccessRights;
import com.l2emu.gameserver.datatables.ArmorSetsTable;
import com.l2emu.gameserver.datatables.AugmentationData;
import com.l2emu.gameserver.datatables.CharNameTable;
import com.l2emu.gameserver.datatables.CharTemplateTable;
import com.l2emu.gameserver.datatables.ClanTable;
import com.l2emu.gameserver.datatables.DoorTable;
import com.l2emu.gameserver.datatables.EventDroplist;
import com.l2emu.gameserver.datatables.ExtractableItemsData;
import com.l2emu.gameserver.datatables.FishTable;
import com.l2emu.gameserver.datatables.GmListTable;
import com.l2emu.gameserver.datatables.HelperBuffTable;
import com.l2emu.gameserver.datatables.HennaTable;
import com.l2emu.gameserver.datatables.HennaTreeTable;
import com.l2emu.gameserver.datatables.HeroSkillTable;
import com.l2emu.gameserver.datatables.ItemMarketTable;
import com.l2emu.gameserver.datatables.ItemTable;
import com.l2emu.gameserver.datatables.JailSpawnTable;
import com.l2emu.gameserver.datatables.LevelUpData;
import com.l2emu.gameserver.datatables.MapRegionTable;
import com.l2emu.gameserver.datatables.MerchantPriceConfigTable;
import com.l2emu.gameserver.datatables.NobleSkillTable;
import com.l2emu.gameserver.datatables.NpcBufferTable;
import com.l2emu.gameserver.datatables.NpcTable;
import com.l2emu.gameserver.datatables.NpcWalkerRoutesTable;
import com.l2emu.gameserver.datatables.PcColorTable;
import com.l2emu.gameserver.datatables.PetSkillsTable;
import com.l2emu.gameserver.datatables.ResidentialSkillTable;
import com.l2emu.gameserver.datatables.SkillSpellbookTable;
import com.l2emu.gameserver.datatables.SkillTable;
import com.l2emu.gameserver.datatables.SkillTreeTable;
import com.l2emu.gameserver.datatables.SpawnTable;
import com.l2emu.gameserver.datatables.StaticObjects;
import com.l2emu.gameserver.datatables.SummonItemsData;
import com.l2emu.gameserver.datatables.TeleportLocationTable;
import com.l2emu.gameserver.geoeditorcon.GeoEditorListener;
import com.l2emu.gameserver.handler.AdminCommandHandler;
import com.l2emu.gameserver.handler.ChatHandler;
import com.l2emu.gameserver.handler.ItemHandler;
import com.l2emu.gameserver.handler.MasterHandler;
import com.l2emu.gameserver.handler.SkillHandler;
import com.l2emu.gameserver.handler.UserCommandHandler;
import com.l2emu.gameserver.handler.VoicedCommandHandler;
import com.l2emu.gameserver.idfactory.IdFactory;
import com.l2emu.gameserver.instancemanager.AirShipManager;
import com.l2emu.gameserver.instancemanager.AuctionManager;
import com.l2emu.gameserver.instancemanager.BoatManager;
import com.l2emu.gameserver.instancemanager.CastleManager;
import com.l2emu.gameserver.instancemanager.CastleManorManager;
import com.l2emu.gameserver.instancemanager.ClanHallManager;
import com.l2emu.gameserver.instancemanager.CoupleManager;
import com.l2emu.gameserver.instancemanager.CursedWeaponsManager;
import com.l2emu.gameserver.instancemanager.DayNightSpawnManager;
import com.l2emu.gameserver.instancemanager.DimensionalRiftManager;
import com.l2emu.gameserver.instancemanager.FortManager;
import com.l2emu.gameserver.instancemanager.FortSiegeManager;
import com.l2emu.gameserver.instancemanager.FourSepulchersManager;
import com.l2emu.gameserver.instancemanager.GrandBossManager;
import com.l2emu.gameserver.instancemanager.InstanceManager;
import com.l2emu.gameserver.instancemanager.ItemsOnGroundManager;
import com.l2emu.gameserver.instancemanager.MercTicketManager;
import com.l2emu.gameserver.instancemanager.PetitionManager;
import com.l2emu.gameserver.instancemanager.QuestManager;
import com.l2emu.gameserver.instancemanager.RaidBossPointsManager;
import com.l2emu.gameserver.instancemanager.RaidBossSpawnManager;
import com.l2emu.gameserver.instancemanager.SiegeManager;
import com.l2emu.gameserver.instancemanager.TransformationManager;
import com.l2emu.gameserver.instancemanager.ZoneManager;
import com.l2emu.gameserver.instancemanager.leaderboards.ArenaManager;
import com.l2emu.gameserver.instancemanager.leaderboards.FishermanManager;
import com.l2emu.gameserver.model.AutoChatHandler;
import com.l2emu.gameserver.model.AutoSpawnHandler;
import com.l2emu.gameserver.model.L2Manor;
import com.l2emu.gameserver.model.L2PetDataTable;
import com.l2emu.gameserver.model.L2World;
import com.l2emu.gameserver.model.entity.Hero;
import com.l2emu.gameserver.model.entity.events.CTF;
import com.l2emu.gameserver.model.entity.events.TvT;
import com.l2emu.gameserver.model.olympiad.Olympiad;
import com.l2emu.gameserver.network.L2GameClient;
import com.l2emu.gameserver.network.L2GamePacketHandler;
import com.l2emu.gameserver.pathfinding.PathFinding;
import com.l2emu.gameserver.script.faenor.FaenorScriptEngine;
import com.l2emu.gameserver.scripting.CompiledScriptCache;
import com.l2emu.gameserver.scripting.L2ScriptEngineManager;
import com.l2emu.gameserver.taskmanager.AutoAnnounceTaskManager;
import com.l2emu.gameserver.taskmanager.KnownListUpdateTaskManager;
import com.l2emu.gameserver.taskmanager.TaskManager;
import com.l2emu.gameserver.util.DynamicExtension;
import com.l2emu.gameserver.util.Util;
import com.l2emu.status.Status;
import com.l2emu.util.DeadLockDetector;
import com.l2emu.util.Version;

/**
 * This class ...
 * 
 * @version $Revision: 1.29.2.15.2.19 $ $Date: 2005/04/05 19:41:23 $
 */
public class L2GameServer
{
	private static final Logger _log = Logger.getLogger(L2GameServer.class.getName());
	
	private final SelectorThread<L2GameClient> _selectorThread;
	private final DeadLockDetector _deadDetectThread;
	public static L2GameServer gameServer;
	private LoginServerThread _loginThread;
	private static Status _statusServer;
	public static final Calendar dateTimeServerStarted = Calendar.getInstance();
	
	public SelectorThread<L2GameClient> getSelectorThread()
	{
		return _selectorThread;
	}
	
	public DeadLockDetector getDeadLockDetectorThread()
	{
		return _deadDetectThread;
	}
	
	public L2GameServer() throws Exception
	{
		System.setProperty("python.home", ".");
		
		long serverLoadStart = System.currentTimeMillis();
		
		gameServer = this;
		
		//Inits Database
		// -------------
		Util.printSection("Database");
		L2DatabaseFactory.getInstance();
		
		// load script engines
		Util.printSection("Script Engine");
		L2ScriptEngineManager.getInstance();
		
		Util.printSection("World");
		L2World.getInstance();
		
		if (Config.IS_TELNET_ENABLED)
		{
            new Status(Server.serverMode);
        	_statusServer.start();
		}
		else
			_log.info("Telnet Server is currently disabled.");
		MapRegionTable.getInstance();
		
		Announcements.getInstance();
		AutoAnnounceTaskManager.getInstance();
		
		Util.printSection("IDFactory");
		IdFactory.getInstance();
		_log.config("IdFactory: Free ObjectID's remaining: " + IdFactory.getInstance().size());
				
		ThreadPoolManager.getInstance();
		
		Util.printSection("GeoData");
		GeoData.getInstance();
		if (Config.GEODATA >= 2)
			PathFinding.getInstance();
		
		
		if (Config.ACCEPT_GEOEDITOR_CONN)
			GeoEditorListener.getInstance();
		
		StaticObjects.getInstance();
		GameTimeController.getInstance();
		TeleportLocationTable.getInstance();
		BoatManager.getInstance();
		AirShipManager.getInstance();
		InstanceManager.getInstance();
		
		Util.printSection("TaskManagers");
		KnownListUpdateTaskManager.getInstance();
		
		Util.printSection("Skills");
		SkillTreeTable.getInstance();
		SkillTable.getInstance();
		NobleSkillTable.getInstance();
		HeroSkillTable.getInstance();
		ResidentialSkillTable.getInstance();
		PetSkillsTable.getInstance();
		
		Util.printSection("Items");
		ItemTable.getInstance();
		ArmorSetsTable.getInstance();
		AugmentationData.getInstance();
		SkillSpellbookTable.getInstance();
		SummonItemsData.getInstance();
		ExtractableItemsData.getInstance();
		FishTable.getInstance();
		if (Config.SAVE_DROPPED_ITEM)
			ItemsOnGroundManager.getInstance();
		
		if (Config.AUTODESTROY_ITEM_AFTER > 0
		        || Config.HERB_AUTO_DESTROY_TIME > 0)
			ItemsAutoDestroy.getInstance();
		MerchantPriceConfigTable.getInstance();
		TradeController.getInstance();
		RecipeController.getInstance();
		
		Util.printSection("Characters");
		AccessLevels.getInstance();
		AdminCommandAccessRights.getInstance();
		CharNameTable.getInstance();
		CharTemplateTable.getInstance();
		PcColorTable.getInstance();
		LevelUpData.getInstance();
		HelperBuffTable.getInstance();
		HennaTable.getInstance();	
		HennaTreeTable.getInstance();
		if (Config.L2JMOD_ALLOW_WEDDING)
			CoupleManager.getInstance();
		// Init of a cursed weapon manager
		CursedWeaponsManager.getInstance();
		ClanTable.getInstance();
		CrestCache.getInstance();
		Hero.getInstance();
		
		NpcTable.getInstance();
		NpcBufferTable.getInstance();
		HtmCache.getInstance();
		if (Config.ALLOW_NPC_WALKERS)
			NpcWalkerRoutesTable.getInstance().load();
		L2PetDataTable.getInstance().loadPetsData();
		
		Util.printSection("Seven Signs");
		SevenSigns.getInstance();
		SevenSignsFestival.getInstance();
		
		Util.printSection("Entities and zones");
		ClanHallManager.getInstance();
		DoorTable.getInstance();
		CastleManager.getInstance();
		SiegeManager.getInstance();
		FortManager.getInstance();
		FortSiegeManager.getInstance();
		ZoneManager.getInstance();
		MercTicketManager.getInstance();
		DoorTable.getInstance().registerToClanHalls();
		DoorTable.getInstance().setCommanderDoors();

		Util.printSection("Quests");
		QuestManager.getInstance();
		TransformationManager.getInstance();
		
		try
		{
			Util.printSection("Events/Scripts");
			File scripts = new File(Config.DATAPACK_ROOT + "/data/scripts.cfg");
			L2ScriptEngineManager.getInstance().executeScriptList(scripts);
		}
		catch (IOException ioe)
		{
			_log.severe("Failed loading scripts.cfg, no script going to be loaded");
		}
		try
		{
			CompiledScriptCache compiledScriptCache = L2ScriptEngineManager.getInstance().getCompiledScriptCache();
			if (compiledScriptCache == null)
			{
				_log.info("Compiled Scripts Cache is disabled.");
			}
			else
			{
				compiledScriptCache.purge();
				
				if (compiledScriptCache.isModified())
				{
					compiledScriptCache.save();
					_log.info("Compiled Scripts Cache was saved.");
				}
				else
				{
					_log.info("Compiled Scripts Cache is up-to-date.");
				}
			}
			
		}
		catch (IOException e)
		{
			_log.log(Level.SEVERE, "Failed to store Compiled Scripts Cache.", e);
		}
		QuestManager.getInstance().report();
		TransformationManager.getInstance().report();

		EventDroplist.getInstance();

		Util.printSection("Faenor");
		FaenorScriptEngine.getInstance();
		
		if (Config.ARENA_ENABLED)
			ArenaManager.getInstance().engineInit();
		if (Config.FISHERMAN_ENABLED)
			FishermanManager.getInstance().engineInit();
		
		SpawnTable.getInstance();
		if (Config.JAIL_SPAWN_SYSTEM)
			JailSpawnTable.getInstance().loadJailSpawns();
		DayNightSpawnManager.getInstance().notifyChangeMode();
		RaidBossSpawnManager.getInstance();
		GrandBossManager.getInstance().initZones();
		RaidBossPointsManager.init();
		// Spawn the Orators/Preachers if in the Seal Validation period.
		SevenSigns.getInstance().spawnSevenSignsNPC();
		
		Util.printSection("Economy");
		CastleManorManager.getInstance();
		L2Manor.getInstance();
		AuctionManager.getInstance();
		ItemMarketTable.getInstance();
		
		Util.printSection("Olympiad");
		Olympiad.getInstance();
		
		Util.printSection("DimensionalRift");
		DimensionalRiftManager.getInstance();
		
		Util.printSection("FourSepulchers");
		FourSepulchersManager.getInstance().init();
		
		Util.printSection("Extensions");
		DynamicExtension.getInstance();
		
		Util.printSection("Handlers");
		AutoChatHandler.getInstance();
		AutoSpawnHandler.getInstance();
		_log.config("AutoChatHandler: Loaded " + AutoChatHandler.getInstance().size() + " handlers in total.");
		_log.config("AutoSpawnHandler: Loaded " + AutoSpawnHandler.getInstance().size() + " handlers in total.");
		
		AdminCommandHandler.getInstance();
		ChatHandler.getInstance();
		ItemHandler.getInstance();
		SkillHandler.getInstance();
		UserCommandHandler.getInstance();
		VoicedCommandHandler.getInstance();
		MasterHandler.main();
		
		Util.printSection("Misc");
		TaskManager.getInstance();
		GmListTable.getInstance();
		PetitionManager.getInstance();
		ForumsBBSManager.getInstance();
		Universe.getInstance();
		
		// checks for enabled auto tvt start up.
		// -------------------------------------
		if (Config.TVT_AUTO_STARTUP_ON_BOOT)
		{
			Util.printSection("TvT");
			ThreadPoolManager.getInstance().scheduleGeneral(new Runnable()
			{
				//loads data and start a new event.
				// -------------------------------------
				public void run()
				{
					TvT.loadData();
					TvT.autoEvent();
				}
				//Config.FIRST_TVT_DELAY  minutes till first event start it.
				// -------------------------------------
			}, Util.convertMinutesToMiliseconds(Config.FIRST_TVT_DELAY));
		}
		
		// checks for enabled auto ctf start up.
		// -------------------------------------
		if (Config.CTF_AUTO_STARTUP_ON_BOOT)
		{
			Util.printSection("CTF");
			ThreadPoolManager.getInstance().scheduleGeneral(new Runnable()
			{
				//loads data and start a new event.
				// -------------------------------------
				public void run()
				{
					CTF.loadData();
					CTF.autoEvent();
				}
				//Config.FIRST_CTF_DELAY  minutes till first event start it.
				// -------------------------------------
			}, Util.convertMinutesToMiliseconds(Config.FIRST_CTF_DELAY));
		}
		
		Shutdown.getInstance();
		Runtime.getRuntime().addShutdownHook(Shutdown.getInstance());

		if (Config.DEADLOCK_DETECTOR)
		{
			_deadDetectThread = new DeadLockDetector();
			_deadDetectThread.setDaemon(true);
			_deadDetectThread.start();
		}
		else
			_deadDetectThread = null;
		System.gc();

		printMemUsage();		
		
		_loginThread = LoginServerThread.getInstance();
		_loginThread.start();
		
		L2GamePacketHandler gph = new L2GamePacketHandler();
		SelectorConfig<L2GameClient> sc = new SelectorConfig<L2GameClient>(null, null, gph, gph);
		sc.setMaxSendPerPass(12);
		sc.setSelectorSleepTime(20);
		
		_selectorThread = new SelectorThread<L2GameClient>(sc, gph, gph, null);
		
		InetAddress bindAddress = null;
		if (!Config.GAMESERVER_HOSTNAME.equals("*"))
		{
			try
			{
				bindAddress = InetAddress.getByName(Config.GAMESERVER_HOSTNAME);
			}
			catch (UnknownHostException e1)
			{
				_log.severe("WARNING: The L2GameServer bind address is invalid, using all avaliable IPs. Reason: " + e1.getMessage());
				
				if (Config.DEVELOPER)
					e1.printStackTrace();
			}
		}
		
		try
		{
			_selectorThread.openServerSocket(bindAddress, Config.PORT_GAME);
		}
		catch (IOException e)
		{
			_log.severe("FATAL: Failed to open server socket. Reason: " + e.getMessage());
			if (Config.DEVELOPER)
				e.printStackTrace();
			
			System.exit(1);
		}
		_selectorThread.start();
		_log.config("Maximum Numbers of Connected Players: " + Config.MAXIMUM_ONLINE_USERS);
		long serverLoadEnd = System.currentTimeMillis();
		_log.info("Total Boot Time: " + ((serverLoadEnd - serverLoadStart) / 1000) + " seconds");

		//Print general infos related to GS & DP
		// --------------------------------
		Util.printSection("L2Emu Project: GameServer");
		_log.info("GS Revision: " + Config.IMPLEMENTATION_BUILD + " - build date " + Config.BUILD_DATE);
		_log.info("DP Revision: " + Config.DATAPACK_REVISION + " - build date " + Config.DATAPACK_BUILD_DATE);
		_log.info("Stable Release: " + Version.STABLE_RELEASE);
		_log.info("JDK Version: " + Config.BUILD_JDK);
		_log.info("Archiver-Version: " + Config.ARCHIVER_VERSION);
		_log.info("Created-By: " + Config.CREATED_BY);
		_log.info("Built-By: " + Config.BUILT_BY);
		_log.info("Manifest-Version: " + Config.MANIFEST_VERSION);
		_log.info("http://www.l2-emu.net");
	}
	
	public static void printMemUsage()
	{
		Util.printSection("Memory");
		for (String line : Util.getMemUsage())
			_log.info(line);
	}
}
